import random
import string
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont


class ImageCaptcha:
	def __init__(self, width=120, height=45, length=4, font_size=24):
		self.width = width
		self.height = height
		self.length = length
		self.font_size = font_size
		# 验证码字符集，去除容易混淆的字符
		self.characters = string.ascii_letters + string.digits
		# 尝试加载系统字体，这里使用Windows自带的黑体
		try:
			# Windows系统黑体字体
			self.font = ImageFont.truetype("C:/Windows/Fonts/simhei.ttf", self.font_size)
		except:
			try:
				# Windows系统Arial字体
				self.font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", self.font_size)
			except:
				# 如果都找不到，使用默认字体
				self.font = ImageFont.load_default()
				print("警告：无法加载指定字体，使用默认字体替代")

	def generate_captcha(self):
		# 创建空白图像和绘图对象
		image = Image.new('RGB', (self.width, self.height), (255, 255, 255))
		draw = ImageDraw.Draw(image)

		# 生成随机验证码文本
		captcha_text = ''.join(random.choice(self.characters) for _ in range(self.length))

		# 绘制验证码文本
		for i, char in enumerate(captcha_text):
			# 随机位置和颜色
			x = 10 + i * (self.font_size + 5)
			y = random.randint(0, self.height - self.font_size)
			color = (random.randint(0, 150), random.randint(0, 150), random.randint(0, 150))
			draw.text((x, y), char, font=self.font, fill=color)

		# 绘制干扰线
		for _ in range(5):
			x1 = random.randint(0, self.width)
			y1 = random.randint(0, self.height)
			x2 = random.randint(0, self.width)
			y2 = random.randint(0, self.height)
			draw.line([(x1, y1), (x2, y2)],
					  fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=1)

		# 绘制干扰点
		for _ in range(50):
			draw.point([random.randint(0, self.width), random.randint(0, self.height)],
					   fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

		# 将图像转换为字节流
		buf = BytesIO()
		image.save(buf, 'jpeg')
		buf.seek(0)

		return buf, captcha_text

